<template>
  <avue-crud
    ref="crudRef"
    v-model="formData"
    v-model:page="page"
    :option="option"
    @on-load="getData"
    @row-save="handleSave"
    @row-update="handleUpdate"
    @row-del="handleDelete"
    @search-change="searchChange"
    @search-reset="resetChange"
    @selection-change="selectionChange"
    @row-click="handleRowClick"
    :data="tableData"
  >
  </avue-crud>
</template>
<script setup>
import { ref, getCurrentInstance, onMounted } from 'vue';

const { proxy } = getCurrentInstance();

const props = defineProps({
  config: {
    type: Object,
    default: {},
  },
  // 复显已选中的行
  ids: {
    type: Array,
    default: [],
  },
  // 是否开启选中的最大条数
  // 最大可选条数
  maxSelectionCount: {
    type: Number,
    default: 10,
  },
  // 间距
  searchLabelWidth: {
    type: Number,
    default: 120,
  },
  // 删除展示
  delBtn: {
    type: Boolean,
    default: true,
  },
  editBtn: {
    type: Boolean,
    default: true,
  },
  addBtn: {
    type: Boolean,
    default: true,
  },
  menu: {
    type: Boolean,
    default: true,
  },
});

const crudData = reactive({
  formData: {},
  // 列表数据
  tableData: [],
  // 查询参宿
  queryParams: {},
  // 分页参数
  page: {
    total: 0,
    currentPage: 1,
    pageSize: 10,
  },
  // 选中的数据
  selectData: [],
  // avue配置
  option: {
    searchLabelWidth: props.searchLabelWidth, // searchLabelWidth为标题的宽度，默认为110，可以配置到option下作用于全部,也可以单独配置每一项
    searchIndex: 3,
    searchIcon: true,
    index: true,
    searchEnter: true,
    delBtn: props.delBtn, // table删除按钮
    editBtn: props.editBtn, //table 编辑按钮
    addBtn: props.addBtn, //table添加按钮
    menu: props.menu, // table 操作栏
    selection: true, // table选项
    align: 'center', // table选项
    reserveSelection: true, // 设置reserveSelection为true保留之前的勾选
    rowKey: 'id',
  },
});

const { tableData, formData, queryParams, page, selectData, option } = toRefs(crudData);

const crudRef = ref(null);

onMounted(() => {
  nextTick(() => {
    option.value.column = props.config.column;
    selectData.value = props.ids;
    initRowSelection();
  });
});

// 分页数据
const getData = async () => {
  try {
    const params = {
      ...queryParams.value,
      ...props.config.queryParams,
      size: page.value.pageSize,
      current: page.value.currentPage,
    };
    const res = await props.config.operate.get(params);
    const { code, data } = res.data;
    if (code === 200) {
      tableData.value = data.records;
      page.value.total = data.total;
    }
  } catch (err) {}
};

// 处理新增
const handleSave = async (formData, done, loading) => {
  loading = true;
  await submitForm(formData);
  loading = false;
  done(formData);
};

// 处理编辑
const handleUpdate = async (formData, index, done, loading) => {
  loading = true;
  await submitForm(formData);
  loading = false;
  done(formData);
};

// 删除
const handleDelete = row => {
  const ids = row.id;
  proxy
    .$confirm(`确定将 [${ids}] 数据删除?`, {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
    .then(() => {
      return props.config.operate.remove(ids);
    })
    .then(() => {
      proxy.$message({
        type: 'success',
        message: '操作成功!',
      });
      getData();
    });
};

// 表单提交
const submitForm = async formData => {
  try {
    if (formData.id) {
      const res = await props.config.operate.update(formData);
      const { code, msg } = res.data;
      if (code === 200) {
        getData();
        proxy.$message({
          type: 'success',
          message: msg,
        });
      } else {
        proxy.$message({
          type: 'error',
          message: msg,
        });
      }
    } else {
      const res = await props.config.operate.add(formData);
      const { code, msg } = res.data;
      if (code === 200) {
        getData();
        proxy.$message({
          type: 'success',
          message: msg,
        });
      } else {
        proxy.$message({
          type: 'error',
          message: msg,
        });
      }
    }
  } catch (err) {
    console.error(err);
  }
};

// 搜索
const searchChange = async (params, done) => {
  queryParams.value = params;
  await getData();
  done();
};

// 重置
const resetChange = async params => {
  page.value.currentPage = 1;
  queryParams.value = params;
  await getData();
};

// 切换选中
const initRowSelection = () => {
  let tableIds = tableData.value.map(o => o.id);
  if (!(selectData.value instanceof Array)) return;
  selectData.value.forEach(item => {
    if (tableIds.includes(item.id)) {
      let obj = tableData.value.find(o => o.id == item.id);
      // obj 必须是表格里的某条数据才回显
      crudRef.value.toggleRowSelection(obj, true);
    } else {
      // 用来给当前表格已选择项计数
      crudRef.value.toggleRowSelection(item, true);
    }
  });
};

// 选择变化
const selectionChange = list => {
  selectData.value = list;
  if (list.length > props.maxSelectionCount) {
    const newVal = list.pop();
    crudRef.value.toggleRowSelection(newVal, false);
  }
};

// 点击行选中
const handleRowClick = (row, column, event) => {
  crudRef.value.toggleRowSelection(row);
};

defineExpose({
  selectData,
});
</script>
